<template>
    <div class='box'>
        <!-- 搜索栏 -->
        <div class="search">
            <el-card class="card" shadow="never" :body-style="{ paddingBottom: '0' }">
            <el-form  ref="queryForm" :inline="true">
                <el-form-item>
                    <el-date-picker
                        v-model="transferVal"
                        type="daterange"
                        range-separator="-"
                        :start-placeholder="$t('ztu0TpvwBrwVxjieshushijian')"
                        :end-placeholder="$t('ztu0TpvwBrwVxkaishisjian')"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button @click='searchClick'  type="primary"   icon="ele-Search"> {{ $t('gCfnriWqoYBbtTUitKqI') }} </el-button>
                    <el-button   @click="resetClick" icon="ele-Refresh"> {{ $t('otahMpwpwvM772i15GuCz') }} </el-button>
                    <el-button @click="BulkSubmissionClick" type="primary"   icon="Check"> {{ $t('050Hr71pOlVcojLrFwGdo') }} </el-button>
                </el-form-item>
            </el-form>
            </el-card>
        </div>


        <div class="content">
            <!-- 表格 -->
            <p class="table">
                <el-table :data="list" :row-key="getRowKeys" border v-loading="loading" @select-all="selectAllData" @select="handleSelect" ref="multipleTable" element-loading-background="rgba(0, 0, 0, 0.5)">
                    <el-table-column :reserve-selection="true" type="selection"  width="50" />
                    <el-table-column type="index" :label="$t('3eKEs1bExAXarYpdJemp')" width="100" align="center" :index="indexMethod" />
                    <el-table-column min-width="160" :show-overflow-tooltip="true" prop="v_FileName" :label="$t('zFomb9jE90gMZrSVtgF5q')" align="center" />
                    <el-table-column min-width="160" :show-overflow-tooltip="true" prop="d_CreateTime" :label="$t('qT98SYjsJngYa6KEo2R3Y')" align="center" />
                    <el-table-column min-width="130" :label="$t('rQ5NRdsIr9n8f_8WvQuu')" align="center" fixed="right">
                        <template #default="scope">
                            <el-button @click="playClick(scope.row)" class="icon-e" icon="ele-View" size="small" text type="primary"> {{ $t('b6TYx9jDZpHwIlu0CbhoE') }} </el-button>
                            <!-- <el-button @click="resolveImg(scope.row)" class="icon-e" icon="ele-View" size="small" text type="primary" v-if="isImage(scope.row.file_name)"> {{ $t('h2oGmbyQh9CfK6TapDodm') }} </el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
            </p>
        </div>
         <!-- 页码 -->
         <div class="pagination">
                <el-pagination
                    v-model:currentPage="pageNo" v-model:page-size="pageSize" :total="totalRows" :page-sizes="[10, 20, 50, 100]" small background
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" popper-class="selectBottom" class="page"
                />
        </div>

        <!-- 弹窗 -->
        <el-dialog
            v-model="innerVisible"
            width="50%"
            :title="imgTitle"
            append-to-body
        >
            <el-image :fit="cover" style="width: 100%; min-height: 500px;cursor:pointer;" :preview-src-list="[imgPath]" :src="imgPath">
            </el-image>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRaw, watch, nextTick } from 'vue'
import getTableData from '/@/utils/getTableData'
import { getQueryMediaFileListApi, getQueryBatchIdentificationApi } from '/@/api/its/camera'
import { ElMessage, ElTable, dayjs } from 'element-plus'
export default defineComponent( {
    name: 'drone-media-img',
    components: { },
    props:['isShowDialog', 'item'],
    setup(props,ctx){
        const hostAddress = ref(import.meta.env.VITE_API_URL) // 获取地址
        const innerVisible = ref(false)
        const imgPath = ref('')
        const imgTitle = ref('')
        let srcList:any = []
        let imgOrVideoName = ref('')
        // 搜索类
        const transferVal = ref() // 需要查询的值
        let searchObj:any = reactive({
            v_DeviceCode: props.item.v_RemoteDeviceId || '',
            startTime: '',
            endTime: '',
            timestamp: 0,
        })
        /*** searchClick 查询按钮 */
        const searchClick = () => {
            if(toRaw(transferVal.value) && toRaw(transferVal.value)!== ''){
                searchObj.startTime = toRaw(transferVal.value)[0]
                searchObj.endTime = toRaw(transferVal.value)[1]
                //searchObj.newDate = new Date();
            }else{
                // ElMessage({
                //     type: 'warning',
                //     message: '请选择需要查询的日期',
                //     duration: 1000,
                //     onClose: ()=>{
                //         resetClick()
                //     }
                // })
                searchObj.startTime = null
                searchObj.endTime = null
            }
            // searchObj.timestamp = new Date().getTime();
        }
        /*** resetClick 重置按钮 */
        const resetClick = () => {
            transferVal.value =  ''

            searchObj.v_DeviceCode = props.item.v_RemoteDeviceId || '',
            searchObj.startTime = ''
            searchObj.endTime = ''
            nextTick(()=>{ multipleTable.value!.clearSelection()})
        }
        // 搜索类

        /*** handleClose 关闭事件 */
        const handleClose = (val:any) => {
            ctx.emit('close')
        }

        /*** lookImg 查看图片 */
        const lookImg = (val:any) => {
            srcList = []
            srcList.push(val.file_url)
        }

        /*** playClick 播放事件 */
        const playClick = (val:any) => {
            
            // // imgOrVideoName.value = val.file_name.split('.')[1] || 'JPG'
            // let originRaw = toRaw(val)
            console.log(hostAddress.value + val.v_FileUrl);
            
            imgTitle.value = val.v_FileName
            imgPath.value = hostAddress.value + val.v_FileUrl
            setTimeout(()=>{
                innerVisible.value = true
            },10)
        }

        /** resolveImg 图片识别 */
        const resolveImg = async (row: any,name?:string) => {
            try {
                if(name === 'multi'){
                    
                   return await getQueryBatchIdentificationApi(row);
                }
                let res: any = await getQueryBatchIdentificationApi({
                    v_DeviceCode : props.item.v_RemoteDeviceId || '',
                    imagePathList: row.object_key ? [row.object_key] : row
                })
            } catch (err) { return }
        }

        /** 用于判断是否为图片 */
        // const isImage=computed(()=>(filePath: any)=>{ //计算属性传递参数
        //     let tempExt = filePath.split('.')[1] || 'JPG'
        //     return tempExt === 'JPG' || tempExt === 'jpg'
        // })

        watch(
            ()=> props.item,
            (newVal)=>{
                if(newVal){
                    const t = new Date(new Date().getFullYear(), new Date().getMonth() - 1, new Date().getDate())
                    const startTime = dayjs(t).format('YYYY-MM-DD');
                    transferVal.value = [startTime, dayjs(new Date()).format('YYYY-MM-DD')]
                    searchObj.startTime = startTime
                    searchObj.endTime = dayjs(new Date()).format('YYYY-MM-DD')
                    //
                }else{
                    transferVal.value = []
                }
            },{
                immediate:true
            }
        )


        // 已经选择的数据，在右边渲染
        const selectedAccount:any = ref([]);
        // 选择事件
        const handleSelect = (val:any) => {
            selectedAccount.value = val;
        }

        const getRowKeys  = (val:any) => {
            return val.file_name
        }

        interface MediaFileItem {
            file_id: string;
            file_name: string;
            file_path: string;
            object_key: string;
            is_original: string;
            drone: string;
            payload: string;
            fingerprint: string;
            file_url: string;
            created_time: string;
            file_group_id:string;
            wayline_site_name: string;
            wayline_id: string;
        }

        const multipleTable = ref<InstanceType<typeof ElTable>>();
        // 批量提交图片识别结果
        const BulkSubmissionClick = () => {
            if(selectedAccount.value.length === 0){
                ElMessage({
                    type: 'warning',
                    message: window.$t('xY5DsyOpN_6eJxlyYneVi'),
                    duration: 1000,
                    onClose: ()=>{
                        resetClick()
                    }
                })
                return
            }
            let imageSrc:any = {
                deviceSn :'',
                imageItemList : [],
            };
            selectedAccount.value.forEach((element:MediaFileItem) => {
                imageSrc.deviceSn = props.item.v_RemoteDeviceId
            });
            console.log(imageSrc,"imageSrc");
            selectedAccount.value.forEach(el => {
                imageSrc.imageItemList.push(
                    {
                    imageId: el.n_Id,
                    imageUrl: el.v_FileUrl
                })
            })
            if(imageSrc){
                const name = 'multi'
                resolveImg(imageSrc,name);
                nextTick(()=>{ multipleTable.value!.clearSelection();})
            }
        }

        const checkSelectable = (row:any) => {
            // const name  =  row.object_key.split('.')[1] === 'JPG' ||  row.object_key.split('.')[1] === 'jpg';
            // let canSelect = true;
            // if(selectedAccount.value.length > 0) {
            //     canSelect = selectedAccount.value.every(x => x.file_group_id === row.file_group_id);
            // }
            // return name && row.wayline_id && canSelect ? true : false;
        }

        const selectAllData = (selection:any) => {
            console.log(selection);
            selectedAccount.value = selection;
        }

        return {
            ...getTableData(getQueryMediaFileListApi,{},searchObj),
            // 搜索类
            transferVal,
            resetClick,
            searchClick,
            // 搜索类
            handleClose,
            innerVisible,
            imgPath,
            imgTitle,
            lookImg,
            cover: 'cover',
            playClick,
            imgOrVideoName,
            resolveImg,
            // isImage,
            handleSelect,
            getRowKeys,
            BulkSubmissionClick,
            checkSelectable,
            multipleTable,
            selectAllData,
        }
    },
} )
</script >
<style lang="scss">
.box{
    display: flex;
    flex-direction: column;
    .search{
        display: flex;
        width: 100%;
        .card{
            height: 100%;
        }
    }
    .content{
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .table{
            padding-left: 10px;
        }
    }
    .pagination{
        position: fixed;
        bottom: 0;
        width: 100%;
        height: 60px;
        line-height: 100%;
        background-color: #fff;
        z-index: 99999999;
        .page{
            position: absolute;
            bottom: 0;
            left: 30px;
            line-height: 100%;
        }
    }
}

.selectBottom{
    position: absolute;
    top: auto !important;
    bottom: 34px !important;
    z-index: 99999;
}
</style>